package com.google.code.sharebyblog.bravo;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.code.sharebyblog.bravo.currencyconvertor.domain.CurrencyConversionRequest;
import com.google.code.sharebyblog.bravo.currencyconvertor.domain.CurrencyConversionResponse;
import com.google.code.sharebyblog.bravo.currencyconvertor.service.CurrencyConversionService;



@Controller
public class CurrencyConversionController {
	
	private static final Logger logger = LoggerFactory.getLogger(CurrencyConversionController.class);
	
	@Autowired
	private CurrencyConversionService currencyConversionService;
	
		
	
	/**
	 * Handles conversion request
	 */
	@RequestMapping(value = "/convert/{amount}/{from}/{to}", method = RequestMethod.GET)
	public @ResponseBody CurrencyConversionResponse convert(@PathVariable String amount,@PathVariable String from, @PathVariable String to,HttpServletResponse response) {
		CurrencyConversionResponse currencyConversionresponse = null;
		
		try {
			CurrencyConversionRequest currencyConversionRequest = new CurrencyConversionRequest();
			currencyConversionRequest.setAmount(new BigDecimal(amount));
			currencyConversionRequest.setCurrencyFrom(from);
			currencyConversionRequest.setCurrencyTo(Arrays.asList(to.split(",")));
			
			currencyConversionresponse = currencyConversionService.process(currencyConversionRequest);
			
		} catch (Exception e) {
			logger.error(e.getMessage());
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
		}
		return currencyConversionresponse;
	}
	
}
